package io.renren.modules.app.controller;


import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.PicSuffix;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.RegisterForm;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.utils.FileUtils;
import io.renren.modules.app.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 注册
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-26 17:27
 */
@RestController
@RequestMapping("/app")
@Api("APP注册接口")
public class AppRegisterController {


    private final ResourceLoader resourceLoader;
    @Autowired
    public AppRegisterController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Autowired
    private JwtUtils jwtUtils;
    /**
     * 图片路径
     */
    @Value("${check-car.headPicPath}")
    String headPicPath;
    /**
     * 图片路径
     */
    @Value("${check-car.drivePicPath}")
    String drivePicPath;

    @Autowired
    private UserService userService;

    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@RequestBody RegisterForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        UserEntity userEntity = userService.queryByMobile(form.getMobile());
        if (userEntity != null){
            return R.error("该手机号已注册");
        }

        UserEntity user = new UserEntity();
        user.setMobile(form.getMobile());
        user.setUsername(form.getUsername());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        user.setCreateTime(new Date());
        boolean b = userService.insert(user);
        if (b){
            UserEntity u = userService.queryByMobile(form.getMobile());
            //生成token
            String token = jwtUtils.generateToken(u.getUserId());
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("expire", jwtUtils.getExpire());
            return R.ok(map);
        }

        return R.error("注册失败！");
    }

    /**
     * 上传头像
     * @param file
     * @param u_mobile
     * @return
     */
    @PostMapping("uploadHP/{u_mobile}")
    @ApiOperation("上传头像")
    public R uploadHP(MultipartFile file, @PathVariable("u_mobile") String u_mobile,
                      HttpServletRequest request){


        String filename = u_mobile+ PicSuffix.HEAD_PIC.getSuffix();
        File pic = new File(headPicPath+"/"+filename);
        if (pic.exists()){
            return R.error("头像已存在");
        }
        boolean res = FileUtils.upload(file,headPicPath,filename);

        if (res){
            System.out.println("request.getRequestURL()："+request.getRequestURL());
            System.out.println("上传成功");
            return R.ok("上传成功");
        }
        System.out.println("上传失败啊");
        return R.error("上传失败");
    }

    /**
     * 获取头像
     * @param u_mobile
     * @return
     */
    @GetMapping (value = "showHP/{u_mobile}",produces = MediaType.IMAGE_JPEG_VALUE)
    @ApiOperation("获取头像")
    public ResponseEntity<?> showHP(HttpServletResponse response,
                                    @PathVariable("u_mobile") String u_mobile) {
        try{
            return ResponseEntity.ok(resourceLoader.
                    getResource("file:" +headPicPath+"/"+u_mobile+PicSuffix.HEAD_PIC.getSuffix()));
        }catch (Exception e){
            return ResponseEntity.notFound().build();
        }

    }


}
